﻿using System;
using System.Windows;
using System.Windows.Interactivity;
using Microsoft.Devices;

namespace CCWP7.CaliburnMicro.Behaviors
{
    public interface IVibration
    {
        void Vibrate();
    }

    public class VibrateBehavior : TriggerAction<UIElement>,
    IVibration
    {
        static readonly TimeSpan DefaultTimeSpan = TimeSpan.FromMilliseconds(25);

        #region Vibration Ms Length
        public TimeSpan VibrationMsLength
        {
            get
            {
                return (TimeSpan)GetValue(VibrationMsLengthProperty);
            }
            set
            {
                SetValue(VibrationMsLengthProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store for VibrationMsLength.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty VibrationMsLengthProperty =
        DependencyProperty.Register("VibrationMsLength", typeof(TimeSpan), typeof(VibrateBehavior), new PropertyMetadata(DefaultTimeSpan));
        #endregion

        protected override void OnAttached()
        {
            base.OnAttached();
        }

        protected override void Invoke(object parameter)
        {
            VibrateIfEnabled(VibrationMsLength);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
        }

        internal static void VibrateIfEnabled()
        {
            VibrateIfEnabled(DefaultTimeSpan, null);
        }

        internal static void VibrateIfEnabled(TimeSpan duration)
        {
            VibrateIfEnabled(duration, null);
        }

        internal static void VibrateIfEnabled(TimeSpan duration, bool? enabled)
        {
            var isEnabled = enabled ?? true;// SettingsViewModel.IsVibrationEnabled;

            if (isEnabled == true)
                VibrateController.Default.Start(duration);
        }

        void IVibration.Vibrate()
        {
            VibrateBehavior.VibrateIfEnabled();
        }
    }
}
